package models

import (
	"time"

	"golang.org/x/crypto/bcrypt"
)

type User struct {
	ID             uint      `gorm:"primarykey" json:"id"`
	Name           string    `gorm:"size:50;not null;unique" json:"name"`
	Password       string    `gorm:"size:100;not null" json:"-"`
	Email          string    `gorm:"size:100;unique" json:"email,omitempty"`
	Avatar         string    `json:"avatar,omitempty"`
	Gender         string    `gorm:"size:10" json:"gender,omitempty"`
	Headline       string    `gorm:"size:200" json:"headline,omitempty"`
	Locations      string    `gorm:"type:text" json:"locations,omitempty"`
	Business       string    `gorm:"size:100" json:"business,omitempty"`
	Employments    string    `gorm:"type:text" json:"employments,omitempty"`
	Educations     string    `gorm:"type:text" json:"educations,omitempty"`
	FollowingCount int       `gorm:"default:0" json:"followingCount"`
	FollowerCount  int       `gorm:"default:0" json:"followerCount"`
	LikedCount     int       `gorm:"default:0" json:"likedCount"`
	CreatedAt      time.Time `json:"createdAt"`
	UpdatedAt      time.Time `json:"updatedAt"`

	// 关联
	Following         []*User     `gorm:"many2many:user_followings;foreignKey:ID;joinForeignKey:FollowerID;References:ID;joinReferences:FollowingID" json:"following,omitempty"`
	Followers         []*User     `gorm:"many2many:user_followings;foreignKey:ID;joinForeignKey:FollowingID;References:ID;joinReferences:FollowerID" json:"followers,omitempty"`
	FollowingTopics   []*Topic    `gorm:"many2many:user_following_topics" json:"followingTopics,omitempty"`
	Questions         []*Question `gorm:"foreignKey:QuestionerID" json:"questions,omitempty"`
	Answers           []*Answer   `gorm:"foreignKey:AnswererID" json:"answers,omitempty"`
	LikingAnswers     []*Answer   `gorm:"many2many:user_liking_answers" json:"likingAnswers,omitempty"`
	CollectingAnswers []*Answer   `gorm:"many2many:user_collecting_answers" json:"collectingAnswers,omitempty"`
}

// 加密密码
func (u *User) SetPassword(password string) error {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Password = string(hashedPassword)
	return nil
}

// 校验密码
func (u *User) CheckPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	return err == nil
}
